var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    choose_modal: "none",
    num: 1,
    userList: [],
    specIdList:[],
    specNameList:[],
    twoChoose:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    //获取手机高度
    this.setData({
      navH: app.globalData.navHeight,
    })
    that.setData({
      orderId: options.orderId,
      share: options.share,
      back: options.back,
      groupShoppingId: options.groupShoppingId,
      addrId: options.addrId,
      type: options.type,
      shareBack: options.shareBack,
    });
    wx.request({
      url: app.globalData.url + "getUserAddressList",
      method: "GET",
      data: {
        userId: wx.getStorageSync("userId")
      },
      success: function (res) {
        var data = res.data.data;
        if (res.data.result == 1) {
          if (data.length > 0) {
              console.info(data);
              that.setData({
                data: data.length,
                addrId: data[0].addrId,
              })
          } else {
            that.setData({
              data: 0
            })
          }
        }
      }
    });
  },

  // 计时器
  interval: function () {
    const that = this;
    let timer = setInterval(function () {  // 设置定时器
      var seconds = parseInt(that.data.seconds);
      var minutes = parseInt(that.data.minutes);
      var hours = parseInt(that.data.hours);
      var days = that.data.days;
      seconds--;
      if (seconds <= 0) {
        seconds = 60;
        minutes--;
        if (minutes <= 0) {
          minutes = 59;
          hours--;
          if (hours <= 0) {
            hours = 23;
            days--;
          }
          if (days < 0) {
            clearInterval(timer);
            that.onLoad();
          }
        }
        if (minutes < 10) {
          that.setData({
            minutes: '0' + minutes
          })
        } else {
          that.setData({
            minutes: minutes
          })
        }

      }

      if (seconds < 10) {
        // 少于10补零
        that.setData({
          seconds: '0' + seconds
        })
      } else {
        that.setData({
          seconds: seconds
        })
      }
    }, 1000)
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    that.interval();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.request({
      url: app.globalData.url + "getGroupShoppoingByOrderId",
      method: "GET",
      data: {
        orderId: that.data.orderId
      },
      success: function (res) {
        if (res.data.result==1) {
          var order = res.data;
          var userArr = res.data.groupShoppingHis.userList;
          var product = res.data.product
          var list = [];
          var maxNum = order.groupShoppingHis.totalNum;
          var user1 = { "avatar": "../../img/noTeamer.png" };
          for (var i = 0; i < maxNum; i++) {
            if (i <= userArr.length - 1) {
              //console.log(userArr[i]);
              var user2 = { "avatar": userArr[i].avatar }
              list.push(user2);
              if (userArr[i].userId == wx.getStorageSync("userId")) {//如果已经参与拼团，则将share设置为0
                that.setData({
                  share: 0
                });
              }
            } else {
              list.push(user1);
            }
          };
          //参团人数饱和并且当前用户不属于参团人则跳转首页
          if (userArr.length == that.data.totalNum && that.data.share == 1) {
            wx.showToast({
              title: '手慢无，该团已经拼团成功了！',
              duration: 2000,
              icon: "failed"
            });
            setTimeout(function () {
              wx.reLaunch({
                url: '/pages/mallPage/mallPage',
              })
            }, 2000);
          }
          var sdfDate = order.groupShoppingHis.endTime.replace(/\.|\-/g, "/");
          console.log(sdfDate + ".....")
          var totalSeconds = new Date(sdfDate) - new Date();
          var days = Math.floor(totalSeconds / (24 * 3600 * 1000));
          var leave1 = totalSeconds % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
          var hours = Math.floor(leave1 / (3600 * 1000));
          if (hours < 10) {
            hours = '0' + hours;
          }
          var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
          var minutes = Math.floor(leave2 / (60 * 1000));
          if (minutes < 10) {
            minutes = '0' + minutes;
          }
          var leave3 = leave2 % (60 * 1000);
          var seconds = Math.floor(leave3 / 1000);
          if (seconds < 10) {
            seconds = '0' + seconds;
          }
          that.setData({
            //currentOrder: JSON.stringify(res.data),
            status: order.groupShoppingHis.status,
            totalNum: order.groupShoppingHis.totalNum,
            userList: list,
            currentUserCount: userArr.length,
            product: order.product,
            price: order.product.groupShoppingPrice,
            days: days,
            hours: hours,
            minutes: minutes,
            seconds: seconds,
            hisId: order.groupShoppingHis.hisId,
            product1: product,
            groupShoppingNum: order.groupShoppingHis.groupShoppingNum,
          });
          if(order.product.productSpec!=undefined){
            that.setData({
              productSpec:JSON.parse(order.product.productSpec)
            })
           
          }
          //console.log(parseInt(that.data.seconds));
        } else {
          setTimeout(function () { // 做了个延时重试一次，作为保底。
            wx.showToast({
              title: res.data.errmsg,
              icon: "none",
              duration: 2000,      //停留时间
            })
          }, 500)
         
          wx.navigateBack({
            

          })
        }
      },
        
    });
    //that.interval();
    wx.request({
      url: app.globalData.url + 'getOrderDetails?orderId=' + that.data.orderId,
      method: "get",
      success: function (res) {
        var hisId = res.data.data.groupShoppingHis.hisId;
        wx.getSetting({
          success: res => {
            if (res.authSetting['scope.userInfo']) {
            } else {
              // 未授权，跳转到授权页面
              wx.reLaunch({
                url: '/pages/zcuslist/index?assem=1&orderId=' + that.data.orderId + '&share=1&type=2&groupShoppingId=' + hisId+'&shareBack='+that.data.shareBack
              })
            }
          }
        });
        that.setData({
          currentOrder: res.data.data,
        });
      }
    })


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 跳转拼团订单详情页
   */
  go2AssembleOrderDetail: function (e) {
    var that = this;
    if (that.data.currentOrder == undefined) {
      wx.request({
        url: app.globalData.url + 'getOrderDetails?orderId=' + that.data.orderId,
        method: "get",
        success: function (res) {
          wx.navigateTo({
            url: '/pages/orderDetails/orderDetails?order=' + JSON.stringify(res.data.data) + '&pintuan=1&orderId=' + that.data.orderId,
          })
        }
      })
    } else {
      wx.navigateTo({
        url: '/pages/orderDetails/orderDetails?order=' + JSON.stringify(that.data.currentOrder) + '&pintuan=1&orderId=' + that.data.orderId,
      })
    }


  },
  /**
     * 跳转到产品详情
     */
  toProduct: function (res) {
    var productid = res.currentTarget.dataset.productid;
    wx.navigateTo({
      url: '/pages/productDetail/productDetail?productid=' + productid + '&type=2',
    })

  },
  joinAssemble: function () {
     var that = this;
    if(that.data.productSpec != undefined){
      if(!that.data.twoChoose){
        wx.showToast({
          title: '请选择规格',
          icon:'none'
        })
        return;
      }
      
  }

    if(that.data.priceId!=undefined){
      var specString = "";
      for(var i=0;i<that.data.specNameList.length;i++){
        specString+=that.data.specNameList[i]+"-";
      }
      specString = specString.substring(0,specString.length-1);
      var plist = '[{"productId":"' + that.data.product.productId + '","num":' + that.data.num + ',"price":' + that.data.price + ',"title":"' + that.data.product.title + '","thumbnailImage":"' + that.data.product.thumbnailImage +'","specPriceId":' +that.data.priceId  +',"specString":"' +specString + '","point":0}]';
    }else{
      plist = '[{"productId":"' + that.data.product.productId + '","num":' + that.data.num + ',"price":' + that.data.price + ',"title":"' + that.data.product.title + '","thumbnailImage":"' + that.data.product.thumbnailImage + '","point":0}]';
    }
   
    console.info(plist);
    wx.navigateTo({
      url: '/pages/confirmOrder/confirmOrder?userId=' + wx.getStorageSync("userId") + '&pAndNList=' + plist + '&type=2&index=0&groupShoppingId=' + that.data.groupShoppingId+'&addrId='+that.data.addrId
    })
    that.modal_none();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // 弹出
  modal_show: function (e) {
    var flag = e.currentTarget.dataset.flag;
    this.setData({
      flag: flag,
      choose_modal: "block",
    });
  },
  //消失
  modal_none: function () {
    this.setData({
      choose_modal: "none",
      // choose1_modal: "none",
      // choose2_modal: "none",
      num: 1,
    });
  },
  /* 点击减号 */
  bindMinus: function () {
    var num = this.data.num;
    // 如果大于1时，才可以减
    if (num > 1) {
      num--;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <=
      1 ? 'disabled' :
      'normal';
    // 将数值与状态写回
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
  //加号
  bindPlus: function (e) {
    var num = this.data.num;
    // 不作过多考虑自增1
    if (num >= this.data.product.inventoryQuantity) {
      return;
    }
    num++;

    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <
      1 ? 'disabled' :
      'normal';
    // 将数值与状态写回
    //console.info(this.data.product.seckillLimitNum);
    if (this.data.product.seckillLimitNum > 0) {
      if (num > this.data.product.seckillLimitNum) {
        wx.showToast({
          title: '超过限购数量',
          icon: "none"
        })
        return;
      }
    }

    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that = this;
    console.info("这是id" + that.data.orderId);
    console.info("这是id" + that.data.hisId);

    return {
      title: "发送给好友",
      imageUrl: that.data.product.thumbnailImage,
      path: '/pages/assembleDetail/assembleDetail?orderId=' + that.data.orderId + '&share=1&type=2&groupShoppingId=' + that.data.hisId + '&shareBack=1',
    }
  },

  navBack: function () {
    var that = this;
    console.info(that.data.back);
    if (that.data.back == 1) {
      wx.navigateBack({
        delta:3
      })
    } else if (that.data.shareBack == 1) {
      wx.switchTab({
        url: '/pages/mallPage/mallPage',
      })
    } else {
      wx.navigateBack({

      })
    }

  },
  rules: function () {
    wx.navigateTo({
      url: '/pages/webView/webView?url=' + app.globalData.url + 'getWebPage&webId=groupShoopingRules',
    });
  },
  chooseSpec:function(e){
    var that = this;
    var specIdList = that.data.specIdList;
    var specNameList = that.data.specNameList;
    if(specIdList[e.currentTarget.dataset.index] == e.currentTarget.dataset.id){
      specIdList[e.currentTarget.dataset.index] = "";
      specNameList[e.currentTarget.dataset.index] = "";
      that.setData({
        specIdList:specIdList,
        specNameList:specNameList,
        twoChoose:false,
        price:that.data.product1.groupShoppingPrice
      })
      return;
    }
    specIdList[e.currentTarget.dataset.index] = e.currentTarget.dataset.id;
    specNameList[e.currentTarget.dataset.index] = e.currentTarget.dataset.name;
    that.setData({
      specIdList:specIdList,
      specNameList:specNameList,
    })
        console.log(specIdList)
         var specIdlistString = "";
          for(var i=0;i<specIdList.length;i++){
            specIdlistString+=specIdList[i]+",";
          }
        specIdlistString = specIdlistString.substring(0,specIdlistString.length-1);
        wx.request({
          url: app.globalData.url + "bySpecGetProudctPrice",
          data: {
            productId: that.data.product.productId,
            specIdList:specIdlistString,
            userId: wx.getStorageSync("userId")
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            if (res.data.result == 1) {
              if(res.data.data.inventoryQuantity > 0){
                  that.setData({
                    price:res.data.data.groupShoppingPrice,
                    priceId:res.data.data.priceId,
                    inventoryQuantity:res.data.data.inventoryQuantity
                  })
              }else{
                wx.showToast({
                  title: '库存不足',
                  icon:"none"
                })
              }
              
              
            }
            for(var i=0;i<that.data.specIdList.length;i++){
              if(that.data.specIdList[i] == undefined || that.data.specIdList[i] == ""||that.data.specIdList.length < that.data.productSpec.length){
                  that.setData({
                    twoChoose:false,
                    price:that.data.product1.groupShoppingPrice,
                  })
              }else{
                that.setData({
                  twoChoose:true,
                })
              }
            }
          },
        })
        // for(var i=0;i<that.data.specIdList.length;i++){
        //   if(that.data.specIdList[i] == undefined || that.data.specIdList[i] == ""||that.data.specIdList.length < that.data.productSpec.length){
        //       that.setData({
        //         twoChoose:false,
        //         price:that.data.price1,
        //       })
        //   }
        // }
  }
})